﻿@page "/login"
@using System.Web;
@layout EmptyLayout
@inject Task<HttpClient> tHttp

<div style="width: 300px;
    margin: auto auto;
    margin-top: 20%;">

    <h3>Login</h3>
    <Space Direction="@DirectionVHType.Vertical">
        <SpaceItem>
            <AntDesign.Input 
            AutoFocus="true"
                            Placeholder="please input token" 
                            Size="large" @bind-Value="@token"
                            OnPressEnter="()=>SetToken()"
                            Type="password">
                <Prefix><Icon Type="lock" /></Prefix>
            </AntDesign.Input>
        </SpaceItem>
        <SpaceItem>
            <Spin Spinning="Loading" Size="large" Tip="验证中...">
                <Button Type="primary" @onclick="() => SetToken()" Class="submit" Size="large" Block>提&nbsp;交</Button>
            </Spin>
        </SpaceItem>
    </Space>
    </div>



@code {
    public string token { get; set; }
    bool Loading { get; set; }

    async Task SetToken()
    {
        Loading = true;

        var uri = navigationManager.ToAbsoluteUri(navigationManager.Uri);
        var urlpath = HttpUtility.ParseQueryString(uri.Query).Get("src") ?? "";

        // user login
        var Http = await tHttp;
        Http.DefaultRequestHeaders.Clear();
        Http.DefaultRequestHeaders.Add("token",token);
        var result = await Http.GetStringAsync("/token");

        if (result == "ok")
        {
            await js.InvokeVoidAsync("localStorage.setItem", "token", token);
            navigationManager.NavigateTo("/" + urlpath);
        }
        else
        {
            Loading = false;
            _ = _message.Error(result);
        }
        StateHasChanged();
    }
}
